package cn.ibizlab.eam.core.util.job;

import cn.ibizlab.eam.core.eam_core.domain.PLANSCHEDULE;
import cn.ibizlab.eam.core.eam_core.service.IPLANSCHEDULEService;
import cn.ibizlab.eam.core.util.helper.CronUtil;
import cn.ibizlab.eam.util.client.IBZTaskFeignClient;
import cn.ibizlab.eam.util.dict.StaticDict;
import cn.ibizlab.eam.util.domain.JobsInfoDTO;
import cn.ibizlab.eam.util.security.AuthenticationUser;
import com.baomidou.jobs.api.JobsResponse;
import com.baomidou.jobs.exception.JobsException;
import com.baomidou.jobs.handler.IJobsHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.util.Date;


@Slf4j
@Component("EAMServiceJobHandler")
public class EAMServiceJobHandler implements IJobsHandler {

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMPlanService emplanService;

    @Autowired
    private IPLANSCHEDULEService iplanscheduleService;

    @Autowired
    private IBZTaskFeignClient ibzTaskFeignClient;

    @Override
    public JobsResponse execute(String tenantId, String param) throws JobsException {
        AuthenticationUser curUser= AuthenticationUser.getAuthenticationUser();
        curUser.setUserid("SYSTEM");
        curUser.setPersonname("系统管理员");
        TestingAuthenticationToken authentication = new TestingAuthenticationToken(curUser,null);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        cn.ibizlab.eam.core.eam_core.domain.EMPlan entity=new cn.ibizlab.eam.core.eam_core.domain.EMPlan();
        //","分隔 一个是计划id，一个是计划时刻设置id
        String[] planParam = param.split(",");
        //"="分隔，把属性和参数分隔开，拿到计划id值
        String[] EMPLANParam = planParam[0].split("=");
        //"="分隔，把属性和参数分隔开，拿到计划时刻设置id值
        String[] PlanscheduleParam = planParam[1].split("=");

        entity.set(EMPLANParam[0], EMPLANParam[1]);
        emplanService.createWO(entity);
        //计划时刻设置id
        String planScheduleId = PlanscheduleParam[1];
        PLANSCHEDULE planschedule = iplanscheduleService.get(planScheduleId);
        //获取cron值，通过计划时刻设置类型判断该计划是每天、每周、每月、自己制定
        String cron = "";
        if (StringUtils.compare(planschedule.getScheduletype(), StaticDict.CODELIST_SCHEDULETYPE.ITEM_3.getValue()) == 0){
            cron= CronUtil.createMonthCronExpression(planschedule);
        }else if (StringUtils.compare(planschedule.getScheduletype(), StaticDict.CODELIST_SCHEDULETYPE.ITEM_4.getValue()) == 0){
            cron = CronUtil.createWeekCronExpression(planschedule);
        }else if (StringUtils.compare(planschedule.getScheduletype(), StaticDict.CODELIST_SCHEDULETYPE.ITEM_5.getValue()) == 0){
            cron = CronUtil.createDayCronExpression(planschedule);
        }else if (StringUtils.compare(planschedule.getScheduletype(), StaticDict.CODELIST_SCHEDULETYPE.ITEM_1.getValue()) == 0){
            cron = CronUtil.createCustomizeCronExpression(planschedule);
        }else if (StringUtils.compare(planschedule.getScheduletype(), StaticDict.CODELIST_SCHEDULETYPE.ITEM_6.getValue()) == 0){
            cron = CronUtil.createAssignCronExpression(planschedule);
        }
        //通过对应的计划设置类型获取对应的cron，获取下一次时间
        Date nextTriggerTime = CronUtil.getNextTriggerTime(cron);
        //获取总计划设置PLANSCHEDULE表对应数据，得到开始时间和截止时间，判断下一次时间是否在这个时间段内，如果不在直接停止
        //开始时间
        Timestamp cyclestarttime = planschedule.getCyclestarttime();
        //截止时间
        Timestamp cycleendtime = planschedule.getCycleendtime();
        JobsInfoDTO jobsInfoDTO = new JobsInfoDTO();
        if (cyclestarttime==null && cycleendtime==null){
            jobsInfoDTO.setId(planschedule.getTaskid());
            jobsInfoDTO.setStatus(1);
        }else if (cyclestarttime==null && cycleendtime!=null){
            if (cycleendtime.getTime() < nextTriggerTime.getTime()){
                jobsInfoDTO.setId(planschedule.getTaskid());
                jobsInfoDTO.setStatus(1);
            }
        } else if (cycleendtime==null && cyclestarttime!= null){
            if (cyclestarttime.getTime() > nextTriggerTime.getTime()){
                jobsInfoDTO.setId(planschedule.getTaskid());
                jobsInfoDTO.setStatus(1);
            }
        }else if (cyclestarttime!=null && cycleendtime!=null){
            //判断是否在此范围内
            if (cyclestarttime.getTime() > nextTriggerTime.getTime() || cycleendtime.getTime() < nextTriggerTime.getTime()){
                jobsInfoDTO.setId(planschedule.getTaskid());
                jobsInfoDTO.setStatus(1);
            }
        }
        ibzTaskFeignClient.saveJob(jobsInfoDTO);

        log.info("执行 DemoJobHandler tenantId=" + tenantId + ",param=" + param);
        return JobsResponse.ok();
    }
}
